package com.hanm.util;

import java.util.ArrayList;
import java.util.List;

public class StringUtil {

	/**
	 * 校验是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * <ul>
	 * <li>author Administrator</li>
	 * <li>createDate: Mar 24, 2011 10:31:45 AM</li>
	 * <li>comment:根据给定的字符分隔字符串</li>
	 * <p>
	 * </p>
	 * </ul>
	 * 
	 * @param str
	 * @param sp
	 * @return
	 */
	public static String[] splitBy(String str, char sp) {
		if (str == null) {
			return new String[0];
		}
		str = str.trim();
		if (str.equals("")) {
			return new String[0];
		}
		List<String> list = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		boolean inQuote = false;

		int len = str.length();
		for (int i = 0; i < len; ++i) {
			char ch = str.charAt(i);
			if ((ch == '\\') && (i + 1 < len)) {
				++i;
				ch = str.charAt(i);
				sb.append(ch);
			} else {
				if (sb.length() == 0) {
					if ((ch == ' ') || (ch == '\t') || (ch == '\r')) {
						continue;
					}
					if (ch == '\n') {
						continue;
					}
				}
				String s;
				if (i + 1 == len) {
					if ((ch == '"') && (inQuote)) {
						inQuote = false;
						s = sb.toString().trim();
						sb.delete(0, sb.length());
						list.add(s);
						break;
					}
					if (ch != sp) {
						sb.append(ch);
						s = sb.toString().trim();
						sb.delete(0, sb.length());
						list.add(s);
						break;
					}
					s = sb.toString().trim();
					sb.delete(0, sb.length());
					list.add(s);
					list.add("");

					break;
				}
				if ((ch == sp) && (!(inQuote))) {
					s = sb.toString().trim();
					sb.delete(0, sb.length());
					list.add(s);
				} else if ((ch == '"') && (sb.length() == 0) && (str.indexOf(34, i + 1) > 0)) {
					inQuote = true;
				} else if ((ch == '"') && (inQuote)) {
					inQuote = false;
				} else {
					sb.append(ch);
				}
			}
		}
		String[] ret = new String[list.size()];
		list.toArray(ret);
		return ret;
	}
}
